package cn.bingo.yunsj.utils;

import java.io.*;
import java.security.acl.Owner;

import cn.bingo.yunsj.common.exception.EmException;
import cn.bingo.yunsj.common.exception.OwnException;
import cn.bingo.yunsj.mail.model.FileProperties;
import org.apache.log4j.Level;
import org.docx4j.Docx4jProperties;
import org.docx4j.convert.out.pdf.PdfConversion;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.fonts.*;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.utils.Log4jConfigurator;

public class WordToPDFConvertor {

	public static void wordToPDFConvertor(String wordPath,String pdfPath) {

		try {
			InputStream is = new FileInputStream(wordPath);
			WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);

			//解决中文乱码
			Mapper fontMapper = new BestMatchingMapper();
			fontMapper.getFontMappings().put("Algerian", PhysicalFonts.getPhysicalFonts().get("Arial Unicode MS"));
			fontMapper.getFontMappings().put("隶书", PhysicalFonts.getPhysicalFonts().get("LiSu"));
			fontMapper.getFontMappings().put("宋体",PhysicalFonts.getPhysicalFonts().get("SimSun"));
			fontMapper.getFontMappings().put("微软雅黑",PhysicalFonts.getPhysicalFonts().get("Microsoft Yahei"));
			fontMapper.getFontMappings().put("黑体",PhysicalFonts.getPhysicalFonts().get("SimHei"));
			fontMapper.getFontMappings().put("楷体",PhysicalFonts.getPhysicalFonts().get("KaiTi"));
			fontMapper.getFontMappings().put("新宋体",PhysicalFonts.getPhysicalFonts().get("NSimSun"));
			fontMapper.getFontMappings().put("华文行楷", PhysicalFonts.getPhysicalFonts().get("STXingkai"));
			fontMapper.getFontMappings().put("华文仿宋", PhysicalFonts.getPhysicalFonts().get("STFangsong"));
			fontMapper.getFontMappings().put("宋体扩展",PhysicalFonts.getPhysicalFonts().get("simsun-extB"));
			fontMapper.getFontMappings().put("仿宋",PhysicalFonts.getPhysicalFonts().get("FangSong"));
			fontMapper.getFontMappings().put("仿宋_GB2312",PhysicalFonts.getPhysicalFonts().get("FangSong_GB2312"));
			fontMapper.getFontMappings().put("幼圆",PhysicalFonts.getPhysicalFonts().get("YouYuan"));
			fontMapper.getFontMappings().put("华文宋体",PhysicalFonts.getPhysicalFonts().get("STSong"));
			fontMapper.getFontMappings().put("华文中宋",PhysicalFonts.getPhysicalFonts().get("STZhongsong"));
			wordMLPackage.setFontMapper(fontMapper);
			PdfSettings pdfSettings = new PdfSettings();

			//Converting docx to PDF and putting into output folder
			OutputStream out = new FileOutputStream(pdfPath);
			PdfConversion converter = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);

			// Turning off debug which may get printed on converted PDF
			Docx4jProperties.getProperties().setProperty("docx4j.Log4j.Configurator.disabled", "true");
			Log4jConfigurator.configure();
			org.docx4j.convert.out.pdf.viaXSLFO.Conversion.log.setLevel(Level.OFF);

			converter.output(out, pdfSettings);
		} catch (Throwable e) {
			throw new OwnException(EmException.SYSTEM_EXCPTION,e.getMessage());
		}
	}
}